package com.htbb.controller.pay;

import java.net.URLDecoder;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.htbb.common.base.MappingConfig;
import com.htbb.common.base.PropertiesConfig;
import com.htbb.common.base.Result;
import com.htbb.common.base.exception.BizException;
import com.htbb.common.msgBodyAdvice.CryptionType;
import com.htbb.model.pay.ReqOfPayment;
import com.htbb.model.personalInsure.dto.Channel;
import com.htbb.order.entity.TcIsu;
import com.htbb.order.interfaces.TcIsuService;
import com.htbb.pay.interfaces.TcPayService;


/**
 * 支付接口
 * @author wuyongde
 *
 */
@Controller
@RequestMapping(value = "pay")
public class ApplyPayController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private TcIsuService tcIsuService;
	@Autowired
	private TcPayService tcPayService;
	
	@CryptionType
	@ResponseBody
	@RequestMapping(value = "/applyPay", method = { RequestMethod.POST }, produces = "application/json;charset=UTF-8")
	public Object applyPay(HttpServletRequest request, HttpServletResponse response,
			@RequestBody ReqOfPayment reqOfPayment)
			throws Exception {

		Result<Object> result = new Result<Object>();
		
		Channel channel = MappingConfig.getChannel(reqOfPayment.getPartnerCode().toUpperCase());
		if("0".equals(channel.getIsPaylimit())){
			throw new BizException("无调用支付接口权限！");
		}
		TcIsu tcIsu = tcIsuService.getTcIsuDetail(reqOfPayment.getHbCode());
		
		if(tcIsu == null || tcIsu.getIsuStatus() == null){
        	logger.info("*************无效的核保单号");
        	return  new Result<Object>("201","无效的核保单号");
        }
		if(tcIsu.getIsuStatus() != 0){
			if(tcIsu.getIsuStatus() == 8){
	        	logger.info("*************订单已经取消");
	        	return  new Result<Object>("202","订单已经取消");
	        }
			if(tcIsu.getIsuStatus() == 1 || tcIsu.getIsuStatus() == 2){
	        	logger.info("*************该核保单号已经支付，请勿重复支付");
	        	return  new Result<Object>("203","该核保单号已经支付，请勿重复支付");
	        }
        }
		
		//单位RMB元，精确到小数字点后两位
		String amt = Float.parseFloat(reqOfPayment.getTotalMoney())/100+"";
		
		if(!reqOfPayment.getTotalMoney().equals(tcIsu.getIsuFee()+"")){
        	logger.error("*************金额与实际金额不符，支付失败");
        	return  new Result<Object>("204","金额与实际金额不符，支付失败,收到金额："+reqOfPayment.getTotalMoney()+
        			",实际金额："+tcIsu.getIsuAmt());
        }
		
		if(!StringUtils.isEmpty(reqOfPayment.getNotifyUrl())){
			reqOfPayment.setNotifyUrl(URLDecoder.decode(reqOfPayment.getNotifyUrl()));
		}
		
		//alipay-wxpay-unionpay，支付方式多种提供中横线隔开
		String pay_channel = reqOfPayment.getPay_channel()==null?"alipay-wxpay-unionpay":reqOfPayment.getPay_channel();
		String prod_type= "N";  // N普通产品  C受控产品
		
		SortedMap<String, Object> paramMap = new TreeMap<String,Object>();
		paramMap.put("request_charset", "UTF-8");
		paramMap.put("sign_type", "MD5");
		paramMap.put("out_trade_no", tcIsu.getOrderId());
		paramMap.put("prod_type", prod_type);
		paramMap.put("merchant_code", PropertiesConfig.merchantCode);
		paramMap.put("subject", reqOfPayment.getBody());
		paramMap.put("body", reqOfPayment.getBody());
		paramMap.put("return_url", reqOfPayment.getSurl());
		paramMap.put("amt", amt);
		paramMap.put("pay_channel", pay_channel);
		paramMap.put("notify_url", reqOfPayment.getNotifyUrl());
		paramMap.put("fail_url", reqOfPayment.getFurl());
		
		String sign= HaiTunPayUtil.getSign(paramMap, PropertiesConfig.haiTunKey);
		
		StringBuffer payUrl = new StringBuffer();
		payUrl.append(PropertiesConfig.payAction);
		payUrl.append("?request_charset=UTF-8&sign_type=MD5");
		payUrl.append("&body="+reqOfPayment.getBody());
		payUrl.append("&subject="+reqOfPayment.getBody());
		payUrl.append("&notify_url="+reqOfPayment.getNotifyUrl());
		payUrl.append("&out_trade_no="+tcIsu.getOrderId());
		payUrl.append("&merchant_code="+PropertiesConfig.merchantCode);
		payUrl.append("&amt="+amt);
		payUrl.append("&pay_channel="+pay_channel);
		payUrl.append("&prod_type="+prod_type);
		payUrl.append("&return_url="+reqOfPayment.getSurl());
		payUrl.append("&fail_url="+reqOfPayment.getFurl());
		payUrl.append("&sign="+sign);
	
		return new Result<Object>(payUrl.toString());
	}
	
	
	
}
